<?php

namespace App\library\services;


use Elasticsearch\ClientBuilder;

class EsSearchService
{
    protected $client;

    protected $host = '121.4.89.192:9200';

    /**
     * EsSearchService constructor.
     * 初始化连接es
     */
    public function __construct()
    {
        $this->client = ClientBuilder::create()->setHosts([$this->host])->build();
    }

    /**
     * Author:Yingbo Sun
     * 检测索引是否存在
     * @param $index
     * @return bool
     */
    public function existIndex($index)
    {
        $params = ['index' => $index];
        return $this->client->indices()->exists($params);
    }


    /**
     * Author:Yingbo Sun
     * 创建索引
     * @param $index
     * @param $params
     */
    public function setIndex($params)
    {
        //指定分词
        $res = $this->client->indices()->create($params);
        if ($res){
            echo '成功';
        }

    }

    /**
     * Author:Yingbo Sun
     * 添加数据
     * @param $index
     * @param $data
     * @param int $id
     */
    public function add($index,$data,$id = 0)
    {
        $params = [
            'index' => $index,
            'type' => '_doc',
            'id' => $id,
            'body' => [
                $data
            ]
        ];
        $response = $this->client->index($params);
    }

    /**
     * Author:Yingbo Sun
     *商品搜索
     * @param $params
     * @return array
     */
    public function match($params)
    {
        $results = $this->client->search($params);
        return $results;
    }

    /**
     * Author:Yingbo Sun
     * 删除索引
     * @param $params
     * @return array
     */
    public function delIndex($params)
    {
        $response = $this->client->indices()->delete($params);
        return $response;
    }

    /**
     * Author:Yingbo Sun
     * 更新索引
     * @param $params
     * @return array
     */
    public function updateIndex($params)
    {
        $response = $this->client->update($params);
        return $response;
    }


}
